//
//  AddressViewController.m
//  AppointmentForCar
//
//  Created by Herron on 2016/11/16.
//  Copyright © 2016年 Herron. All rights reserved.
//

#import "AddressViewController.h"
#import "SearchNearPointViewController.h"
#import "GeoCodeSearchManager.h"
#import "AddressModel.h"

@interface AddressViewController ()<SearchNearPointViewControllerDelegate, BMKMapViewDelegate, BMKLocationServiceDelegate>

@property (weak, nonatomic) IBOutlet UILabel *homeLabel;
@property (weak, nonatomic) IBOutlet UILabel *companyLabel;

@property (strong, nonatomic) BMKMapView *mapView;
@property (nonatomic, strong) BMKLocationService *locService;
@property (nonatomic , strong) GeoCodeSearchManager * searchAddress;

@property (nonatomic , copy) NSString * cityName;

@property (nonatomic, copy) NSString *type; // 家/公司
@property (nonatomic, strong) AddressModel *addressModel;


@end

@implementation AddressViewController
{
    BMKPointAnnotation * _annotation;
    BMKAnnotationView * _annotationView;
    BMKPoiInfo * _destinationInfo;
    BOOL _isUserLocation;
    BOOL _isDecoding;
}

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"常用地址";
    _mapView = [[BMKMapView alloc] init];
    _locService = [[BMKLocationService alloc]init];

    NSString *userId = [UserAccountManager shareUserManager].user.userId;
    [NetWork postNetWorkWithUrl:kURLUserCommonAddress parame:@{@"id":userId} successBlock:^(NSDictionary *dic) {
        NSLog(@"常用地址dic = %@", dic);
        
        NSError *error;
        self.addressModel = [[AddressModel alloc] initWithDictionary:dic[@"data"] error:&error];
        NSLog(@"address = %@, error = %@", self.addressModel, error);
        self.homeLabel.text = self.addressModel.homeAddress ;
        self.companyLabel.text = self.addressModel.companyAddress;
    } errorBlock:^(id error) {
        [HUDManager showWarningWithText:@"网络异常"];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    _mapView.delegate = self;
    _locService.delegate = self;
    [_locService startUserLocationService];
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - BMKMapViewDelegate
- (void)mapView:(BMKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{
    _annotation.title = @"";
    _annotationView.paopaoView.hidden = YES;
    [_annotation setCoordinate:_mapView.centerCoordinate];
}

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    if(!_isUserLocation)
    {
        return;
    }
    [_annotation setCoordinate:_mapView.centerCoordinate];
    _isDecoding = YES;
    _annotation.title = @"";
    _annotationView.paopaoView.hidden = YES;
    [self.searchAddress reverseGeocodeSearchOptionWithLocationCoordinate2D:_mapView.centerCoordinate results:^(NSString *address , NSString * city) {
        _annotation.title = address;
        _cityName = city;
        _annotationView.paopaoView.hidden = NO;
        [_annotationView setSelected:YES animated:YES];
        _isDecoding = NO;
    }];
}
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    [_annotation setCoordinate:_mapView.centerCoordinate];
    [self.searchAddress reverseGeocodeSearchOptionWithLocationCoordinate2D:_mapView.centerCoordinate results:^(NSString *address , NSString * cityName) {
        _annotation.title = address;
        _cityName = cityName;
        _annotationView.paopaoView.hidden = NO;
        [_annotationView setSelected:YES animated:YES];
    }];
}
- (void)mapView:(BMKMapView *)mapView onDrawMapFrame:(BMKMapStatus*)status
{
    [_annotation setCoordinate:_mapView.centerCoordinate];
    
}
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    // 生成重用标示identifier
    NSString *AnnotationViewID = @"xidanMark";
    
    // 检查是否有重用的缓存
    BMKAnnotationView* annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    annotationView.canShowCallout = YES;
    annotationView.draggable = YES;
    [annotationView setSelected:YES animated:YES];
    _annotationView = annotationView;
    
    return annotationView;
}

#pragma mark - BMKLocationServiceDelegate
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_locService stopUserLocationService];
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
        _locService.userLocation.location.coordinate.longitude};
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;
    [_mapView setCenterCoordinate:pt];
    if(!_annotationView)
    {
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
        pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
            _locService.userLocation.location.coordinate.longitude};
        _annotation = [[BMKPointAnnotation alloc] init];
        [_annotation setCoordinate:pt];
        [_mapView addAnnotation:_annotation];
    }
    _isUserLocation = YES;
}


#pragma mark - <SearchNearPointViewControllerDelegate>
- (void)searchNearPointWithResult:(BMKPoiInfo *)result {
    NSLog(@"result = %@", result);
    NSString *str = [NSString stringWithFormat:@"%@ %@", result.name, result.address];
    if ([self.type isEqualToString:@"1"]) {
        self.homeLabel.text = str;
        [NetWork postNetWorkWithUrl:kURLHomeAddress parame:@{@"commonHomeAddress":str} successBlock:^(NSDictionary *dic) {
            NSLog(@"家 = %@", dic);
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"网络异常"];
        }];
    } else if ([self.type isEqualToString:@"2"]) {
        self.companyLabel.text = str;
        [NetWork postNetWorkWithUrl:kURLCompanyAddress parame:@{@"commonCompanyAddress":str} successBlock:^(NSDictionary *dic) {
            NSLog(@"公司 = %@", dic);
        } errorBlock:^(id error) {
            [HUDManager showWarningWithText:@"网络异常"];
        }];
    }
}

#pragma event method
- (IBAction)homeClick:(id)sender {
    self.type = @"1";
    [self search];
}

- (IBAction)companClick:(id)sender {
    self.type = @"2";
    [self search];
}

- (void)search {
    SearchNearPointViewController *controller = [[SearchNearPointViewController alloc] init];
    controller.cityName = self.cityName;
    NSLog(@"cityName = %@", self.cityName);
    controller.delegate = self;
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - private method
- (GeoCodeSearchManager *)searchAddress
{
    if(!_searchAddress)
    {
        _searchAddress = [[GeoCodeSearchManager alloc] init];
    }
    return _searchAddress;
}



@end
